
package com.example.filedownandjson.controller.update;

import com.example.filedownandjson.controller.update.bean.LineageOsUpdateBean;
import com.example.filedownandjson.controller.update.bean.ROM;
import com.example.filedownandjson.utils.Md5Utils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Controller
public class LineageOsController {
    @RequestMapping("/api/v1/polaris/unofficial/{communityId}")
    @ResponseBody
    public LineageOsUpdateBean checkUpdate(HttpServletRequest request, @PathVariable String communityId) {
        LineageOsUpdateBean bean = new LineageOsUpdateBean();
        List<ROM> romList = new ArrayList<>();
        ROM rom = new ROM();
        Calendar calendar = Calendar.getInstance();
        long time = calendar.getTimeInMillis();

        rom.setDatetime(time / 1000);  // 刷机包打包时间,此值越大，就能刷机
        rom.setFilename("signed-ota_update.zip");
        rom.setId(Md5Utils.md5("D://ROM/signed-ota_update.zip")); // 刷机包的Md5
        rom.setRomtype("UNOFFICIAL"); // 非官方的
        rom.setSize(new File("D://ROM/signed-ota_update.zip").length());  // 刷机包大小
        rom.setUrl("http://10.10.110.240:8082/rom/polaris/" + "signed-ota_update.zip"); // 刷机包URL
        rom.setVersion("20.0"); // 刷机包版本
        romList.add(rom);
        bean.setResponse(romList.toArray(new ROM[]{}));
        return bean;
    }

    @RequestMapping(value = "/rom/polaris/{communityId}")
    public void downloadLocal(HttpServletRequest request, HttpServletResponse response, @PathVariable String communityId) throws IOException {
        // 读到流中
        File file = new File("D://ROM/signed-ota_update.zip");
        InputStream inputStream = new FileInputStream(file);// 文件的存放路径
        response.reset();
        response.setContentType("application/x-msdownload");
        // response.setContentType("application/octet-stream");

        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(communityId, StandardCharsets.UTF_8));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }
}
